//
//  ViewControllerInfoVC.swift
//  movieInfo
//
//  Created by zhangkai on 2023/5/13.
//

import UIKit
import GoogleMobileAds
import StatusAlert

class ViewControllerInfoVC: BaseVC {
    //ad
    var isBool = false
    private var rewardedAd: GADRewardedAd?
    
    
    //no ad
    var id: Int!
    var model:Movie?
    
    var topView:ViewControllerInfoView!
    var infoView:ViewControllerSubInfoView!
    var cast:ViewControllerCastInfoView!
    var movies:ViewControllerMoviesInfoView!
    var PreInfo:ViewControllerPreInfoView!
    
    var mainScro:UIScrollView!
    
    private var savelist: [Movie] = []
    
    
    fileprivate let formatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy/MM/dd"
        return formatter
    }()
    
    @objc func shareInfo(){

        
        if let title = self.model?.title{
            let arr:[Any] = [title,
                             topView.bgIMG.image ?? UIImage()]
            let activity = UIActivityViewController(activityItems: arr, applicationActivities: nil)
            activity.completionWithItemsHandler = { (activity,result,items,error)->Void in
            
            }
            self.present(activity, animated: true, completion: nil)
            
        }else{
            let statusAlert = StatusAlert()
            statusAlert.image = UIImage(named: "")
            statusAlert.title = ""
            statusAlert.message = "Sharing failed"
            statusAlert.showInKeyWindow()
        }
        


        
        

        
        
    }
    
    @objc func addToWatchlist(){
        
        
  
        let arr = self.savelist.filter{$0.saveTime == self.formatter.string(from: Date())}
        
        var maxin = 3
        let str = UserDefaults.standard.object(forKey: "isVIP") as? String ?? ""
        if str == "1"{
            maxin = 10
        }
        
        if arr.count > maxin{
            
            let alert = UIAlertController(title: "", message: "The daily free collection times have been used up. Watching advertisements can increase the collection times. Do you want to watch?", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Look", style: .default,handler: { [weak self] action in
                self?.showAD()
            }))
            alert.addAction(UIAlertAction(title: "Cancel", style: .cancel,handler: nil))
            self.present(alert, animated: true)
 
        }else{
            
            
            if model != nil{


                if !self.savelist.contains(where: {$0.id == model!.id}) {

                    let addImage = UIImage(systemName: "checkmark.circle.fill")
                    let watchlistButton = UIBarButtonItem(image: addImage, style: .plain, target: self, action: #selector(remToWatchlist))
                    navigationItem.rightBarButtonItem = watchlistButton

                    let time = self.formatter.string(from: Date())
                    model!.saveTime = time

                    self.savelist.append(model!)
                    UserDefaults.standard.set(try? PropertyListEncoder().encode(self.savelist), forKey: "savefvolist")
                    
                    
                    let statusAlert = StatusAlert()
                    statusAlert.image = UIImage(named: "")
                    statusAlert.title = ""
                    statusAlert.message = "Has been added to the collection"
                    statusAlert.showInKeyWindow()
                }



            }
        }

        
        


        
    }
    
    @objc func remToWatchlist(){
        
        if model != nil{
            
            
            
            if let index = savelist.firstIndex(where: {$0.id == model!.id}) {
                savelist.remove(at: index)
                UserDefaults.standard.set(try? PropertyListEncoder().encode(self.savelist), forKey: "savefvolist")
            }
            
            
            let addImage = UIImage(systemName: "plus.circle")
            let watchlistButton = UIBarButtonItem(image: addImage, style: .plain, target: self, action: #selector(addToWatchlist))
            navigationItem.rightBarButtonItem = watchlistButton
            
            
        }
        
    }



    
    override func viewDidLoad() {
        super.viewDidLoad()
        

    
        
        if let data = UserDefaults.standard.value(forKey: "savefvolist") as? Data {
            let copy = try? PropertyListDecoder().decode([Movie].self, from: data)
            savelist = copy!
        }
        
//        private func addToWatchIcon() {
        
        if model != nil{
            
            
            if !self.savelist.contains(where: {$0.id == model!.id}) {
                
                let addImage = UIImage(systemName: "plus.circle")
                let watchlistButton = UIBarButtonItem(image: addImage, style: .plain, target: self, action: #selector(addToWatchlist))
//                navigationItem.rightBarButtonItem = watchlistButton
                
                
                let addImage1 = UIImage(systemName: "shareplay")
                let watchlistButton1 = UIBarButtonItem(image: addImage1, style: .plain, target: self, action: #selector(shareInfo))
                navigationItem.rightBarButtonItems = [watchlistButton,watchlistButton1]
                
            }else{
                let addImage = UIImage(systemName: "checkmark.circle.fill")
                let watchlistButton = UIBarButtonItem(image: addImage, style: .plain, target: self, action: #selector(remToWatchlist))
//                navigationItem.rightBarButtonItem = watchlistButton
                
                
                let addImage1 = UIImage(systemName: "shareplay")
                let watchlistButton1 = UIBarButtonItem(image: addImage1, style: .plain, target: self, action: #selector(shareInfo))
                navigationItem.rightBarButtonItems = [watchlistButton,watchlistButton1]
          
            }
            
        }
        
        
        id = model?.id
        
        let w = UIScreen.main.bounds.width

        view.backgroundColor = .white
        // Do any additional setup after loading the view.
        mainScro = UIScrollView()
        view.addSubview(mainScro)
        mainScro.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        mainScro.contentSize = CGSize(width: 0, height: 1200)
        
        topView = ViewControllerInfoView()
        mainScro.addSubview(topView)
        topView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.left.equalToSuperview()
            make.width.equalTo(w)
            make.height.equalTo(360)
        }
        topView.backgroundColor = .secondarySystemBackground
        topView.callBlock = { [weak self] in
          
            
            if let path = self?.model?.posterPath {
                let url = "https://image.tmdb.org/t/p/w500\(path)"
                // 网络图片
                let data1 = YBIBImageData()
                data1.imageURL = NSURL(string: url) as URL?
                data1.projectiveView = self?.view
                
                let browser = YBImageBrowser()
                browser.dataSourceArray = [data1]
                browser.show()

//                YBImageBrowser *browser = [YBImageBrowser new];
//                browser.dataSourceArray = @[data0, data1, data2];
//                browser.currentPage = ...;
//                [browser show];
                
                
            }
            

            
        }
        
        
        infoView = ViewControllerSubInfoView()
        mainScro.addSubview(infoView)
        infoView.snp.makeConstraints { make in
            make.top.equalTo(topView.snp.bottom).offset(10)
            make.left.equalToSuperview()
            make.width.equalTo(w)
            make.height.equalTo(150)
        }
//        
        infoView.backgroundColor = .white
//        infoView.infoLabel.text = model?.overview ?? ""
        
        
        cast = ViewControllerCastInfoView()
        mainScro.addSubview(cast)
        cast.snp.makeConstraints { make in
            make.top.equalTo(infoView.snp.bottom).offset(10)
            make.left.equalToSuperview()
            make.width.equalTo(w)
            make.height.equalTo(170)
        }
        cast.backgroundColor = .white
        cast.callBlock = { [weak self] id in
            
            let vc = PersonInfoViewVC()
            vc.id = id
//                personinfo
            self?.navigationController?.pushViewController(vc, animated: true)
        }
        
        
        movies = ViewControllerMoviesInfoView()
        mainScro.addSubview(movies)
        movies.snp.makeConstraints { make in
            make.top.equalTo(cast.snp.bottom).offset(10)
            make.left.equalToSuperview()
            make.width.equalTo(w)
            make.height.equalTo(170)
        }
        movies.backgroundColor = .white
        movies.callBlock = { [weak self] model in
            
            
            let vc = ViewControllerInfoVC()
            vc.model = model
            vc.hidesBottomBarWhenPushed = true
            self?.navigationController?.pushViewController(vc, animated: true)
        }
        
        PreInfo = ViewControllerPreInfoView()
        mainScro.addSubview(PreInfo)
        PreInfo.snp.makeConstraints { make in
            make.top.equalTo(movies.snp.bottom).offset(10)
            make.left.equalToSuperview()
            make.width.equalTo(w)
            make.height.equalTo(170)
        }
        movies.backgroundColor = .white
        
        
        topView.model = self.model
        infoView.infoView.text = self.model?.overview ?? ""
        
        getCast()
        requestMovies(page: 1)
        getVideos()
        
    }
    


    
    
    func getCast(){
        
        
        let urltype = "movie/\(id!)/credits?"
        let requestURL = MMNetWork.shared.searchMovieURL(type: urltype, page: 1)
        MMNetWork.shared.fetchData(urlString: requestURL, castType: [Cast].self,keyPath: "cast") {[weak self] result in
            
                        guard let self = self else { return }
                        switch result {
                        case .success(let cast):
//                            self.updateUI(with: cast)
                            self.cast.model = cast
                            break
                        case .failure(let error):
                            print(error)
                        }
        }

    }
    
    
    func requestMovies(page: Int) {
        let urltype = "movie/\(id!)/similar?"
        let keypath = "results"
     

        let requestURL = MMNetWork.shared.searchMovieURL(type: urltype, page: 1)
        MMNetWork.shared.fetchData(urlString: requestURL, castType: [Movie].self, keyPath: keypath) { [weak self] result in
            guard let self = self else { return }
               switch result {
               case .success(let movies):
//                   self.updateUI(with: movies)
                   self.movies.model = movies
                   break
               case .failure(let error):
                   print(error)
                   break
               }
        }

    }
    
    
    func getVideos(){
        
        
        let requestURL = MMNetWork.shared.getNewMovieURL(ID: "\(id!)", page: 0)
        print(requestURL)
        MMNetWork.shared.fetchData(urlString: requestURL, castType: VideoData.self, keyPath: nil) { [weak self] result in
            guard let self = self else { return }
            switch result {
            case .success(let movies):
//                self.updateUI(with: movies)
//                self.updateUI(with: movies)
                self.PreInfo.preData = movies
                print(movies)
                print("哈哈")
            case .failure(let error):
                print(error)
                print("哈哈")
            }
        }

    }
    
    
    
    
    
    
    
    
    
    
    

}

extension ViewControllerInfoVC:GADFullScreenContentDelegate{
    

    
    func showAD(){
        
        
        let statusAlert = StatusAlert()
        statusAlert.image = UIImage(named: "")
        statusAlert.title = ""
        statusAlert.message = "Advertising loading"
        statusAlert.showInKeyWindow()

        
//        ca-app-pub-3940256099942544/1712485313
//pub-3940256099942544/1712485313
//        ca-app-pub-5223367835995553/7835846466 正式

        let request = GAMRequest()
        GADRewardedAd.load(withAdUnitID:"ca-app-pub-5223367835995553/7835846466",
                           request: request,
                           completionHandler: { [self] ad, error in
            
            self.isBool = false
            
          if let error = error {
            print("Failed to load rewarded ad with error: \(error.localizedDescription)")
              
              let statusAlert = StatusAlert()
              statusAlert.image = UIImage(named: "")
              statusAlert.title = ""
              statusAlert.message = "Loading failed. Please try again later"
              statusAlert.showInKeyWindow()

            return
          }
          rewardedAd = ad
            rewardedAd?.present(fromRootViewController: self, userDidEarnRewardHandler: { [weak self] in
                self?.isBool = true
   
            })
            rewardedAd?.fullScreenContentDelegate = self
          print("Rewarded ad loaded.")
        }
        )
        
        
    }
    
    
    
    
    func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
      print("Ad did fail to present full screen content.")
    }

    /// Tells the delegate that the ad will present full screen content.
    func adWillPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
      print("Ad will present full screen content.")
    }

    /// Tells the delegate that the ad dismissed full screen content.
    func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
      print("Ad did dismiss full screen content.")
        
        if self.isBool{
            print("1")
            
            
            
            if model != nil{
                
                
                if !self.savelist.contains(where: {$0.id == model!.id}) {
                    
                    let addImage = UIImage(systemName: "checkmark.circle.fill")
                    let watchlistButton = UIBarButtonItem(image: addImage, style: .plain, target: self, action: #selector(remToWatchlist))
                    navigationItem.rightBarButtonItem = watchlistButton
                    
                    let time = self.formatter.string(from: Date())
                    model!.saveTime = time
                    
                    self.savelist.append(model!)
                    UserDefaults.standard.set(try? PropertyListEncoder().encode(self.savelist), forKey: "savefvolist")
                    
                    
                    let statusAlert = StatusAlert()
                    statusAlert.image = UIImage(named: "")
                    statusAlert.title = ""
                    statusAlert.message = "Has been added to the collection"
                    statusAlert.showInKeyWindow()
                }
                
                
                
            }
        }else{
            print("2")
        }
    }
}
